﻿using BTL_Cloud.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TL_Cloud.Core.Entities;
using TL_Cloud.Core.Services;
using TL_Cloud.Models.BookShop;
using TL_Cloud.RepositoryInterface.BookShop;
using TL_Cloud.ViewModels.BookShop.BaseUser;

namespace TL_Cloud.RepositoryService.BookShop
{
    /// <summary>
    /// 用户的存储
    /// </summary>
    public class BaseUserRepository : BaseRepository<Base_User>, IBaseUserRepository
    {

        public BaseUserRepository(AppBookShopContext myContext,
       IPropertyMappingContainer propertyMappingContainer) : base(myContext, propertyMappingContainer)
        {
            currentDbSet = _myContext.BaseUser;
        }

        public async Task<PaginatedList<Base_User>> GetAllEntitiesAsync(BaseUserQueryParameters parameters)
        {
            var query = currentDbSet.AsQueryable();

            //if (!string.IsNullOrEmpty(parameters.keyWord))
            //{
            //    string keyword = parameters.keyWord.ToLowerInvariant();
            //    query.Where(n => n.ClassName.ToLowerInvariant().Contains(keyword));
            //}

            query = query.ApplySort(parameters.OrderBy, _propertyMappingContainer.Resolve<BaseUserResource, Base_User>());

            var count = await query.CountAsync();
            var data = await query
                .Skip(parameters.PageIndex * parameters.PageSize)
                .Take(parameters.PageSize)
                .ToListAsync();

            return new PaginatedList<Base_User>(parameters.PageIndex, parameters.PageSize, count, data);
        }
        /// <summary>
        ///获取用户的信息
        /// </summary>
        /// <param name="userCode">用户编号 (可以是用户编号\  手机号 \ 邮箱号码)</param>
        /// <param name="password">用户密码</param>
        /// <returns></returns>
        public async Task<Base_User> GetUserInfo(string userCode, string password)
        {
            return await currentDbSet.FirstOrDefaultAsync(n =>
            (n.UserCode.ToLowerInvariant() == userCode.ToLowerInvariant()
            || n.Telephone.ToLowerInvariant() == userCode.ToLowerInvariant()
            || n.Email.ToLowerInvariant() == userCode.ToLowerInvariant()
            )
            && n.Password.ToLowerInvariant() == password.ToLowerInvariant());
        }
    }
}
